package cn.tkb.org.service.impl;

import cn.tkb.basic.service.IBaseService;
import cn.tkb.basic.service.impl.BaseServiceImpl;
import cn.tkb.basic.util.MD5Utils;
import cn.tkb.basic.util.PageQuery;
import cn.tkb.basic.util.StrUtils;
import cn.tkb.org.domain.Employee;
import cn.tkb.org.mapper.EmployeeMapper;
import cn.tkb.org.query.EmployeeQuery;
import cn.tkb.org.service.IEmployeeService;
import cn.tkb.user.domain.LoginInfo;
import cn.tkb.user.mapper.LoginInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LoginInfoMapper loginInfoMapper;
    @Override
    public void add(Employee employee) {
        //初始化employee里面的salt和加密之后的password
        initEmployee(employee);
        //先保存loginInfo
        LoginInfo loginInfo = employee2loginInfo(employee);
        loginInfoMapper.save(loginInfo);
        employee.setLogininfo_id(loginInfo.getId());
        super.add(employee);
    }

    private LoginInfo employee2loginInfo(Employee employee) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(employee,loginInfo);
        //把employee对应的登录信息的id赋值给登录信息
        loginInfo.setId(employee.getLogininfo_id());
        loginInfo.setType(1);//后端页面注册
        return loginInfo;
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String password = employee.getPassword();
        String md5Pwd = MD5Utils.encrypByMd5(password + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
    }

    @Override
    public void update(Employee employee) {
        LoginInfo loginInfo = loginInfoMapper.loadById(employee.getLogininfo_id());
        String pwd = employee.getPassword();
        //判断一下用户是否修改了密码如果修改了密码那么不需要给员工加密加盐
        if(pwd.equals(loginInfo.getPassword())){
            loginInfo = employee2loginInfo(employee);
            loginInfoMapper.update(loginInfo);
            super.update(employee);
        }else {
            //把修改的信息加密加盐
            initEmployee(employee);
            //把加密加盐之后的员工信息赋值一份给loginInfo
            loginInfo = employee2loginInfo(employee);
            loginInfoMapper.update(loginInfo);
            super.update(employee);
        }

    }

    @Override
    public void delete(Long id) {
        //删除员工id之前要把对应的LoginInfo里面的删掉
        Employee employee = employeeMapper.loadById(id);
        loginInfoMapper.delete(employee.getLogininfo_id());
        super.delete(id);
    }
}
